<?php
/**
 * GoogleAnalyticsApi
 *
 * very simple google analytics api for use with
 * http://wordpress.org/extend/plugins/googleanalyticscounter
 *
 * (c) 2009 by www.yellingnews.com
 *
 */
class GoogleAnalyticsApi {
  /**
   * session token
   */
  var $session;
  /**
   * google analytics account id something like UA-11111-1
   */
  var $account_id;

  function GoogleAnalyticsApi($username, $password) {
    $this->login($username, $password);
  }
  
  function login($username, $password) {
		$data = $this->httpGet('https://www.google.com/accounts/ClientLogin', 'accountType=GOOGLE&Email=' . $username . '&Passwd=' . $password);

    if($data !== false) {
		  $this->session = substr(strstr($data, "Auth="), 5);

      unset($data);
    }
  }
  
  function sliceOut($data, $start, $end) {
    $from = strpos($data, $start) + strlen($start);
    
    if($from === false) {
      return false;
    }

    $to = @strpos($data, $end, $from);
    
    if($to === false) {
      return false;
    }
    
    return substr($data, $from, $to-$from);
  }
  
  function getAccounts() {
    $data = $this->httpGet('https://www.google.com/analytics/feeds/accounts/default', false, 0);

    if(empty($data) || $data === false) {
			return false;
    }

		$accounts = array();
    
    if(preg_match_all('|<entry>(.*?)</entry>|', $data, $matches)) {
      if(count($matches[0]) > 0 ) {
        foreach($matches[0] as $match) {
          $id = $this->sliceOut($match, "<dxp:tableId>", "</dxp:tableId>").'|'.$this->sliceOut($match, "<dxp:property name='ga:webPropertyId' value='", "'/>");
          if($id !== false) {
            $accounts[$id] = $this->sliceOut($match, "<title type='text'>", "</title>");
          }
        }
      }
    }

		return $accounts; 
  }
  
  function getData($what, $start, $end) {
    $url = sprintf('https://www.google.com/analytics/feeds/data?ids=%s&start-date=%s&end-date=%s&metrics=%s', $this->account_id, $start, $end, $what);
		$data = $this->httpGet($url, false, 0);

    if(empty($data) || $data === false) {
			return false;
    }
    
    return $this->sliceOut($data, "<dxp:metric confidenceInterval='0.0' name='ga:visitors' type='integer' value='", "'/></dxp:aggregates>");

	} 
  
  function httpGet($url, $post = false, $header = 1) {
    if(!function_exists('curl_init')) {
      return false;
    }
    
    $handle = curl_init($url);

    if($handle) {
  		curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
  		curl_setopt($handle, CURLOPT_HEADER, $header);
  		curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
  
  		if($this->session) {
  			curl_setopt($handle, CURLOPT_HTTPHEADER, array('Authorization: GoogleLogin auth=' . $this->session));
  		}
  
  		if($post) {
  			curl_setopt($handle, CURLOPT_POST, 1);
  			curl_setopt($handle, CURLOPT_POSTFIELDS, $post. '&service=analytics&source=gaapi');
  		}
      
      $data = curl_exec($handle);
      
      curl_close($handle);
  		
  		return $data;
    }
  }
}

?>